
package cz.results.testperzist.model;

import cz.results.perzist.db4o.DbClientDb4o;
import java.io.IOException;
import java.util.List;

public class ModelDb4o {
    
    private DbClientDb4o dbClient;
    private Startovka sl;
    
    
    public ModelDb4o() {
        try {
            dbClient = new DbClientDb4o();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    public ModelDb4o(String nazev) {
        this();
        sl = dbReadStartovka(nazev);
    }
    
    public DbClientDb4o getDbClient() {
        return dbClient;
    }
    
    public Startovka getStartovka() {
        return sl;
    }
    
    public void setStartovka(Startovka sl) {
        this.sl = sl;
    }

    public void storeZavodnik(Zavodnik zavodnik) {
        try {
            dbClient.dbWrite(zavodnik);
//            dbClient.dbWrite(sl);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
        
    public void addZavodnik(Zavodnik zavodnik) {
        try {
            sl.addZavodnik(zavodnik);
//            dbClient.dbWrite(zavodnik);
            dbClient.dbWrite(sl);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    public void delZavodnik(Zavodnik zavodnik) {
        try {
            sl.delZavodnik(zavodnik);
            dbClient.dbDelete(zavodnik);
            dbClient.dbWrite(sl);            
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    public Startovka dbReadStartovka(String slNazev) {
        List list;
        Startovka retSL = new Startovka(slNazev);
        
        try {
            list = dbClient.dbRead(retSL);
            if (!list.isEmpty()) {
                retSL = (Startovka) list.get(0);
            } else {
                dbWriteStartovka(retSL);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return retSL;
    }
    
    public void dbWriteStartovka(Startovka startovka) {
        try {
            dbClient.dbWrite(startovka);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void refreshSL() {
        sl = (Startovka) dbClient.refresh(sl);

    }

    
}
